package com.zheng.business.web.controller;

import com.zheng.business.common.constant.BusinessResult;
import com.zheng.business.common.constant.BusinessResultConstant;
import com.zheng.business.dao.model.*;
import com.zheng.business.rpc.api.*;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: BusinessAgentBillStatisticsController <br>
 * @Description: TODO <br>
 * @date 2019/8/9 15:48<br>
 **/
@Controller
@RequestMapping("/manage/bill")
@Api(value = "代理账单控制器", description = "代理账单控制器")
public class BusinessAgentBillStatisticsController extends BaseController {

    @Autowired
    BusinessAgentBillStatisticsService businessAgentBillStatisticsService;

    @Autowired
    BusinessAgentBillLogService businessAgentBillLogService;

    @Autowired
    BusinessAgentBillStatisticsLogService businessAgentBillStatisticsLogService;

    @Autowired
    BusinessAgentBillStatisticsUmbrellaOrderService businessAgentBillStatisticsUmbrellaOrderService;

    @Autowired
    BusinessAgentBillStatisticsTimecardOrderService businessAgentBillStatisticsTimecardOrderService;

    @Autowired
    UpmsApiService upmsApiService;

    @Autowired
    BusinessApiService businessApiService;

    @ApiOperation(value = "代理统计账单首页")
    @RequiresPermissions("business:bill:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index(ModelMap modelMap) {
        String loginUserName = this.getLoginUserName();
        Integer upmsAgentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        modelMap.put("currentUserAgentId",upmsAgentId);
        return "/manage/bill/index.jsp";
    }

    @ApiOperation(value = "代理统计账单列表")
    @RequiresPermissions("business:bill:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list() {

        String loginUserName = this.getLoginUserName();
        Integer upmsAgentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        List<Integer> subAgentIdList = null;
        if(upmsAgentId != null && upmsAgentId != Constant.BJS_AGENT_ID){
            subAgentIdList = upmsApiService.selectSubAgentByAgentId(upmsAgentId);
            subAgentIdList.add(upmsAgentId);
        }

        List<Map<String,Object>> billList = businessApiService.getBillStatisticsList(subAgentIdList);

        if(upmsAgentId != null && upmsAgentId != Constant.BJS_AGENT_ID){
            for(Map<String,Object> bill : billList){
                if(bill.get("pid") != null && upmsAgentId.equals(Integer.valueOf(bill.get("id").toString()))){
                    bill.remove("pid");
                }
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("rows", billList);
        return result;
    }

    @ApiOperation(value = "申请提现")
    @RequiresPermissions("business:bill:apply")
    @RequestMapping(value = "/apply/{id}", method = {RequestMethod.GET})
    public String apply(@PathVariable("id") int id, ModelMap modelMap) {
        BusinessAgentBillStatisticsExample example = new BusinessAgentBillStatisticsExample();
        example.createCriteria().andAgentIdEqualTo(id);
        BusinessAgentBillStatistics statistics = businessAgentBillStatisticsService.selectFirstByExample(example);
        modelMap.put("billStatistics", statistics);
        return "/manage/bill/apply.jsp";
    }

    @ApiOperation(value = "申请提现")
    @RequiresPermissions("business:bill:apply")
    @ResponseBody
    @RequestMapping(value = "/apply/{id}", method = {RequestMethod.POST})
    public Object apply(@PathVariable("id") int id,BusinessAgentBillLog businessAgentBillLog) {
        BusinessAgentBillStatistics statistics = businessAgentBillStatisticsService.selectByPrimaryKey(id);
        BusinessAgentBillLogExample example = new BusinessAgentBillLogExample();
        BusinessAgentBillLogExample.Criteria criteria = example.createCriteria();
        criteria.andAgentIdEqualTo(statistics.getAgentId());
        List<Integer> statusList = new ArrayList<Integer>();
        statusList.add(3);//失败
        statusList.add(4);//失败
        statusList.add(5);//撤销
        criteria.andStatusNotIn(statusList);
        int total = businessAgentBillLogService.countByExample(example);
        if(total > 0){
            return new BusinessResult(BusinessResultConstant.FAILED, "已经申请过提现，请不要重复申请。");
        }
        if(businessAgentBillLog.getAmount().compareTo(statistics.getAmountRemainder())==1){
            return new BusinessResult(BusinessResultConstant.FAILED, "余额不足。");
        }
        if(statistics.getAmountRemainder().longValue() == 0){
            return new BusinessResult(BusinessResultConstant.FAILED, "余额不足。");
        }

        businessAgentBillLog.setAgentId(statistics.getAgentId());
        businessAgentBillLog.setAmountTotal(statistics.getAmountRateTotal());
        businessAgentBillLog.setAmountRemainder(statistics.getAmountRemainder());
        businessAgentBillLog.setApplyUser(getLoginUserName());
        businessAgentBillLog.setCreateTime(new Date());
        businessAgentBillLog.setStatus(1);
        businessAgentBillLog.setId(null);
        int count = businessAgentBillLogService.insertSelective(businessAgentBillLog);
        return new BusinessResult(BusinessResultConstant.SUCCESS, count);
    }


    @ApiOperation(value = "账单详情")
    @RequiresPermissions("business:bill:log")
    @RequestMapping(value = "/log/{id}", method = {RequestMethod.GET})
    public String log(@PathVariable("id") int id, ModelMap modelMap) {
        modelMap.put("agentId", id);
        return "/manage/bill/log.jsp";
    }


    @ApiOperation(value = "账单详情")
    @RequiresPermissions("business:bill:log")
    @RequestMapping(value = "/logList/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public Object logList(@PathVariable("id") int id,
                          @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                          @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                          @RequestParam(required = false, value = "sort") String sort,
                          @RequestParam(required = false, value = "order") String order) {
        BusinessAgentBillStatisticsLogExample example = new BusinessAgentBillStatisticsLogExample();
        example.createCriteria().andAgentIdEqualTo(id);
        example.setOrderByClause("create_month asc");

        List<BusinessAgentBillStatisticsLog> list = businessAgentBillStatisticsLogService.selectByExampleForOffsetPage(example,offset,limit);
        long total = businessAgentBillStatisticsLogService.countByExample(example);

        Map<String, Object> result = new HashMap<>();
        result.put("rows", list);
        result.put("total",total);
        return result;
    }

    @ApiOperation(value = "账单明细")
    @RequiresPermissions("business:bill:detail")
    @RequestMapping(value = "/detail/{id}", method = {RequestMethod.GET})
    public String detail(@PathVariable("id") int id, ModelMap modelMap) {
        modelMap.put("id", id);
        return "/manage/bill/detail.jsp";
    }

    @ApiOperation(value = "雨伞订单明细")
    @RequiresPermissions("business:bill:detail")
    @RequestMapping(value = "/detail/umbrellaOrderList/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @PathVariable("id") int id,
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        BusinessAgentBillStatisticsLog log = businessAgentBillStatisticsLogService.selectByPrimaryKey(id);


        BusinessAgentBillStatisticsUmbrellaOrderExample example = new BusinessAgentBillStatisticsUmbrellaOrderExample();
        BusinessAgentBillStatisticsUmbrellaOrderExample.Criteria criteria = example.createCriteria();
        criteria.andAgentIdEqualTo(log.getAgentId());
        criteria.andCreateMonthEqualTo(log.getCreateMonth());
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            example.setOrderByClause(sort + " " + order);
        }else{
            example.setOrderByClause(" endtime asc");
        }

        List<BusinessAgentBillStatisticsUmbrellaOrder> rows = businessAgentBillStatisticsUmbrellaOrderService.selectByExampleForOffsetPage(example, offset, limit);
        long total = businessAgentBillStatisticsUmbrellaOrderService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "雨伞订单明细")
    @RequiresPermissions("business:bill:detail")
    @RequestMapping(value = "/detail/timecardOrderList/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object timecardOrderList(
            @PathVariable("id") int id,
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        BusinessAgentBillStatisticsLog log = businessAgentBillStatisticsLogService.selectByPrimaryKey(id);


        BusinessAgentBillStatisticsTimecardOrderExample example = new BusinessAgentBillStatisticsTimecardOrderExample();
        BusinessAgentBillStatisticsTimecardOrderExample.Criteria criteria = example.createCriteria();
        criteria.andAgentIdEqualTo(log.getAgentId());
        criteria.andCreateMonthEqualTo(log.getCreateMonth());
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            example.setOrderByClause(sort + " " + order);
        }else{
            example.setOrderByClause(" endtime asc");
        }

        List<BusinessAgentBillStatisticsTimecardOrder> rows = businessAgentBillStatisticsTimecardOrderService.selectByExampleForOffsetPage(example, offset, limit);
        long total = businessAgentBillStatisticsTimecardOrderService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

}
